/*
 * Created by JFormDesigner on Sat Jul 16 05:09:55 EDT 2011
 */

package ca.etsmtl.log730.projet.view.server;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;

import org.apache.mina.core.service.IoService;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.Bindings;
import org.jdesktop.swingx.JXButton;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXTable;

import ca.etsmtl.log730.projet.controller.server.MainServer;
import ca.etsmtl.log730.projet.view.ServerUI;
import ca.etsmtl.log730.projet.view.files.JXFiles;

import com.jgoodies.forms.factories.CC;
import com.jgoodies.forms.layout.FormLayout;

/**
 * @author Joe Labrosse
 */
public class SwingServerUI extends JXFrame implements ServerUI {
	public SwingServerUI() {
		initComponents();
	}

	private void btStartActionPerformed(ActionEvent e) {
		// TODO add your code here
			serverController.setSetup(getServerSetupPanel().getServerSetup());
			serverController .start();
	}

	private void btCloseActionPerformed(ActionEvent e) {
		// TODO add your code here
		serverController.getAcceptor().unbind();
	}

	private void createUIComponents() {
		// TODO: add custom component creation code here
	}

	public ChannelTableModel getChannelTableModel() {
		return channelTableModel;
	}

	private void thisWindowActivated(WindowEvent e) {
		// TODO add your code here
		update();
	}

	public JXList getLsHistory() {
		return lsHistory;
	}

	public JXServerSetup getServerSetupPanel() {
		return serverSetupPanel;
	}

	private void btKillSessionActionPerformed(ActionEvent e) {
		// TODO add your code here
		for(int s: tblSessions.getSelectedRows()) {
			channelTableModel.getList().get(s).getSession().close(true);
			System.out.println("-- " + channelTableModel.getList().get(s));
			
		}
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		// Generated using JFormDesigner Evaluation license - Joe Labrosse
		btStart = new JXButton();
		btClose = new JXButton();
		serverSetupPanel = new JXServerSetup();
		tabbedPane1 = new JTabbedPane();
		xPanel1 = new JXPanel();
		scrollPane1 = new JScrollPane();
		tblSessions = new JXTable();
		btKillSession = new JXButton();
		xPanel2 = new JXPanel();
		scrollPane2 = new JScrollPane();
		lsHistory = new JXList();
		xPanel3 = new JXPanel();
		scrollPane3 = new JScrollPane();
		xTable1 = new JXTable();
		xPanel4 = new JXPanel();
		scrollPane4 = new JScrollPane();
		xFiles = new JXFiles();
		channelTableModel = new ChannelTableModel();
		defaultListModel1 = new DefaultListModel();
		eventsTableModel1 = new EventsTableModel();

		//======== this ========
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowActivated(WindowEvent e) {
				thisWindowActivated(e);
			}
		});
		Container contentPane = getContentPane();

		//---- btStart ----
		btStart.setText("Start!");
		btStart.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btStartActionPerformed(e);
			}
		});

		//---- btClose ----
		btClose.setText("Close");
		btClose.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btCloseActionPerformed(e);
			}
		});

		//---- serverSetupPanel ----
		serverSetupPanel.setVisible(false);

		//======== tabbedPane1 ========
		{

			//======== xPanel1 ========
			{

				// JFormDesigner evaluation mark
				xPanel1.setBorder(new javax.swing.border.CompoundBorder(
					new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
						"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
						javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
						java.awt.Color.red), xPanel1.getBorder())); xPanel1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});


				//======== scrollPane1 ========
				{
					scrollPane1.setViewportView(tblSessions);
				}

				//---- btKillSession ----
				btKillSession.setText("Kill Session");
				btKillSession.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						btKillSessionActionPerformed(e);
					}
				});

				GroupLayout xPanel1Layout = new GroupLayout(xPanel1);
				xPanel1.setLayout(xPanel1Layout);
				xPanel1Layout.setHorizontalGroup(
					xPanel1Layout.createParallelGroup()
						.addGroup(xPanel1Layout.createSequentialGroup()
							.addContainerGap()
							.addGroup(xPanel1Layout.createParallelGroup()
								.addComponent(scrollPane1, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 700, Short.MAX_VALUE)
								.addComponent(btKillSession, GroupLayout.Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addContainerGap())
				);
				xPanel1Layout.setVerticalGroup(
					xPanel1Layout.createParallelGroup()
						.addGroup(GroupLayout.Alignment.TRAILING, xPanel1Layout.createSequentialGroup()
							.addContainerGap()
							.addComponent(scrollPane1, GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(btKillSession, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addGap(6, 6, 6))
				);
			}
			tabbedPane1.addTab("Clients", xPanel1);


			//======== xPanel2 ========
			{

				//======== scrollPane2 ========
				{
					scrollPane2.setViewportView(lsHistory);
				}

				GroupLayout xPanel2Layout = new GroupLayout(xPanel2);
				xPanel2.setLayout(xPanel2Layout);
				xPanel2Layout.setHorizontalGroup(
					xPanel2Layout.createParallelGroup()
						.addGroup(xPanel2Layout.createSequentialGroup()
							.addContainerGap()
							.addComponent(scrollPane2, GroupLayout.DEFAULT_SIZE, 700, Short.MAX_VALUE)
							.addContainerGap())
				);
				xPanel2Layout.setVerticalGroup(
					xPanel2Layout.createParallelGroup()
						.addGroup(xPanel2Layout.createSequentialGroup()
							.addContainerGap()
							.addComponent(scrollPane2, GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
							.addContainerGap())
				);
			}
			tabbedPane1.addTab("Log", xPanel2);


			//======== xPanel3 ========
			{
				xPanel3.setLayout(new FormLayout(
					"default:grow",
					"default:grow, $lgap, default"));

				//======== scrollPane3 ========
				{
					scrollPane3.setViewportView(xTable1);
				}
				xPanel3.add(scrollPane3, CC.xy(1, 1));
			}
			tabbedPane1.addTab("Users", xPanel3);


			//======== xPanel4 ========
			{
				xPanel4.setLayout(new FormLayout(
					"default:grow",
					"fill:default:grow"));

				//======== scrollPane4 ========
				{
					scrollPane4.setViewportView(xFiles);
				}
				xPanel4.add(scrollPane4, CC.xy(1, 1));
			}
			tabbedPane1.addTab("File", xPanel4);

		}

		GroupLayout contentPaneLayout = new GroupLayout(contentPane);
		contentPane.setLayout(contentPaneLayout);
		contentPaneLayout.setHorizontalGroup(
			contentPaneLayout.createParallelGroup()
				.addGroup(contentPaneLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(contentPaneLayout.createParallelGroup()
						.addComponent(tabbedPane1, GroupLayout.DEFAULT_SIZE, 729, Short.MAX_VALUE)
						.addComponent(serverSetupPanel, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE)
						.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
							.addComponent(btStart, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(btClose, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		contentPaneLayout.setVerticalGroup(
			contentPaneLayout.createParallelGroup()
				.addGroup(contentPaneLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(serverSetupPanel, GroupLayout.PREFERRED_SIZE, 214, GroupLayout.PREFERRED_SIZE)
					.addGap(7, 7, 7)
					.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
						.addComponent(btClose, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btStart, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
					.addComponent(tabbedPane1, GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
					.addContainerGap())
		);
		setSize(765, 500);
		setLocationRelativeTo(getOwner());

		//---- bindings ----
		bindingGroup = new BindingGroup();
		bindingGroup.addBinding(Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
			channelTableModel, tblSessions, BeanProperty.create("model")));
		bindingGroup.addBinding(Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
			defaultListModel1, lsHistory, BeanProperty.create("model")));
		bindingGroup.addBinding(Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
			eventsTableModel1, xTable1, BeanProperty.create("model")));
		bindingGroup.bind();
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	// Generated using JFormDesigner Evaluation license - Joe Labrosse
	private JXButton btStart;
	private JXButton btClose;
	private JXServerSetup serverSetupPanel;
	private JTabbedPane tabbedPane1;
	private JXPanel xPanel1;
	private JScrollPane scrollPane1;
	private JXTable tblSessions;
	private JXButton btKillSession;
	private JXPanel xPanel2;
	private JScrollPane scrollPane2;
	private JXList lsHistory;
	private JXPanel xPanel3;
	private JScrollPane scrollPane3;
	private JXTable xTable1;
	private JXPanel xPanel4;
	private JScrollPane scrollPane4;
	private JXFiles xFiles;
	private ChannelTableModel channelTableModel;
	private DefaultListModel defaultListModel1;
	private EventsTableModel eventsTableModel1;
	private BindingGroup bindingGroup;
	// JFormDesigner - End of variables declaration  //GEN-END:variables

	private MainServer serverController = null;
			
	@Override
	public void setServerController(MainServer msc) {
		serverController =msc;
	}

	@Override
	public MainServer getServerController() {
		return serverController;
	}

	public void update() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				btClose.setEnabled(serverController.isRunning());
				btStart.setEnabled(!serverController.isRunning());
				serverSetupPanel.setEnabled(!serverController.isRunning());
				serverSetupPanel.repaint();
				SwingServerUI.this.channelTableModel.getList().clear();
				btClose.repaint();
				btStart.repaint();
				if(serverController.getHandler() != null) {
					SwingServerUI.this.channelTableModel.setList(serverController.getHandler().getWorkspace().getUsers());
					SwingServerUI.this.eventsTableModel1.setList(serverController.getHandler().getMessagesMap().entrySet());
					SwingServerUI.this.xFiles.getObjectTableModel().setObjects(serverController.getHandler().getWorkspace().getObjects());
				}
				eventsTableModel1.fireTableDataChanged();
				channelTableModel.fireTableDataChanged();
			}
			
		});
	}
	@Override
	public void serviceActivated(IoService arg0) throws Exception {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				setTitle("RUNNING!");
				update();
			}
			
		});
	}

	@Override
	public void serviceDeactivated(IoService arg0) throws Exception {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				setTitle("OFF!");
				update();
			}
			
		});
	}

	@Override
	public void serviceIdle(IoService arg0, IdleStatus arg1) throws Exception {
	}

	@Override
	public void sessionCreated(IoSession arg0) throws Exception {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				update();
			}
			
		});
	}

	@Override
	public void sessionDestroyed(IoSession arg0) throws Exception {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				update();
			}
			
		});
	}
}
